//
//  HMUserAccount.swift
//  SinaWeiBo
//
//  Created by immncjykeny on 2017/5/7.
//  Copyright © 2017年 immncjykeny. All rights reserved.
//

import UIKit

private let accountFile :NSString = "userAccount.json"

//MARK:建立用户账户模型
class HMUserAccount: NSObject {
    //访问令牌
    var access_token :String? //= "2.003a1QyB_e5cdB2bb1552dd1UisHQC"
    
    //用户ID
    var uid :String? //= "1806605374"
    
    //access_token过期时间 时间是秒计算
    //开发者是5年 使用者是3天
    var expires_in:TimeInterval = 0{
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate:Date?
    //用户昵称
    var screen_name:String?
    //用户头像
    var avatar_large:String?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        //加载磁盘文件到二进制数据
        guard let path = accountFile.cz_appendDocumentDir(),
              let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data , options: []) as? [String:Any] else {
                return
        }
        //使用yy_modelSet设置属性
       yy_modelSet(with: dict ?? [:])
        
        print("从沙盒加载用户信息\(self)")
        //判断token是否过期
        //测试过期日期
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            access_token = nil
            uid = nil
        }
        //删除用户文件
        _ = try? FileManager.default.removeItem(atPath: path)
        
    }
    //保存用户账户信息数据
    func saveAccount(){
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String:Any] ?? [:]
        //删除expires_in
        dict.removeValue(forKey: "expires_in")
        //把子典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            //设置存储沙盒位置 使用Document 存储
             let filePath = accountFile.cz_appendDocumentDir()
            else {
            return
        }
        //保存在磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户信息存储\(filePath)")
    }

}
